package kz.kstu.scantest.desktop.ui.dialog;

import kz.kstu.scantest.app.delegate.api.GuideDelegate;
import kz.kstu.scantest.app.delegate.impl.GuideDelegateImpl;
import kz.kstu.scantest.business.entity.guide.School;
import kz.kstu.scantest.business.util.StringUtil;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.awt.event.*;
import java.util.List;

public class SchoolGuide extends JDialog {

    private final static Logger LOGGER = Logger.getLogger(SchoolGuide.class);

    private final static int WIDTH = 640;
    private final static int HEIGHT = 480;
    private static final String TITLE = "Справочник школ";
    private static final String INPUT_MESSAGE = "Введите название:";
    private static final String DELETE_RECORD_QUESTION = "Вы действительно хотите удалить запись?";
    private static final String CAN_NOT_REMOVE_RECORD = "Не могу удалить запись. Возможно она используется.";

    private JPanel rootPanel;
    private JButton addButton;
    private JButton deleteButton;
    private JList schoolList;
    private JButton editButton;
    private DefaultListModel listModel;

    private GuideDelegate guideDelegate = new GuideDelegateImpl();

    public SchoolGuide() {

    }

    public void initStaticComponents() {
        setContentPane(rootPanel);
        setModal(true);
        setSize(WIDTH, HEIGHT);
        setTitle(TITLE);

        listModel = new DefaultListModel();
        schoolList.setModel(listModel);
        schoolList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        initListeners();
    }


    public void initData() {
        List<School> schoolList = guideDelegate.findSchools();
        for (School school : schoolList) {
            listModel.addElement(school);
        }
    }

    private void initListeners() {
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                add();
            }
        });

        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                edit();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                delete();
            }
        });

        // call delete() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onClose();
            }
        });

        rootPanel.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                 onClose();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void add() {
        String name = JOptionPane.showInputDialog(this, INPUT_MESSAGE, TITLE, JOptionPane.QUESTION_MESSAGE);
        if (!StringUtil.isEmptyString(name)) {
            School school = new School();
            school.setName(name.trim());
            School savedSchool = guideDelegate.saveSchool(school);
            listModel.addElement(savedSchool);
        }
    }

    private void edit() {
        School school = (School) schoolList.getSelectedValue();
        int index = listModel.indexOf(school);
        String name = (String) JOptionPane.showInputDialog(this, INPUT_MESSAGE, TITLE, JOptionPane.QUESTION_MESSAGE,
                null, null, school.getName());
        if (!StringUtil.isEmptyString(name)) {
            school.setName(name.trim());
            guideDelegate.saveSchool(school);
            listModel.remove(index);
            listModel.add(index, school);
        }
    }

    private void delete() {
        int dialogResult = JOptionPane.showConfirmDialog(this, DELETE_RECORD_QUESTION, TITLE, JOptionPane.YES_OPTION);
        if (dialogResult == JOptionPane.YES_OPTION) {
            School school = (School) schoolList.getSelectedValue();
            try {
                guideDelegate.removeSchool(school);
                listModel.removeElement(school);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, CAN_NOT_REMOVE_RECORD, TITLE, JOptionPane.ERROR_MESSAGE);
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

    private void onClose() {
        dispose();
    }
}
